package com.gemantic.task.job;

import java.lang.reflect.ParameterizedType;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;

public abstract class BaseJobHandler<V> extends IJobHandler {

    @Override
    public void execute() throws Exception {
        String param = XxlJobHelper.getJobParam();
        V v = initParams(param);
        this.process(v);
        XxlJobHelper.handleSuccess();
    }

    /**
     * 执行任务
     *
     * @param paramDto 任务参数
     * @return 返回结果
     * @throws Exception
     */
    public abstract void process(V paramDto) throws Exception;

    /**
     * 初始化参数，将字符串转为实体
     *
     * @param param 字符串
     * @return 实体
     */
    @SuppressWarnings("unchecked")
    private V initParams(String param) {
        if (StringUtils.isBlank(param)) {
            return null;
        }
        Class<V> tClass = (Class<V>) ((ParameterizedType) getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[0];
        if (tClass == String.class) {
            return (V) param;
        }
        return JSON.parseObject(param, tClass);
    }
}